<template>
  <div class="order-management">
    <el-row>
        <el-button type="text" class="back-button" @click="goBack">
            <el-icon><ArrowLeft /></el-icon>
            <span>返回</span>
        </el-button>
        <div class="panel-header">
              <h2 class="panel-title">我的订单</h2>
        </div>
    </el-row>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <div class="container">
        <div class="content-wrapper">
          <!-- 左侧菜单 -->
          <div class="sidebar">
            <h3 class="sidebar-title">订单状态</h3>
            <el-menu
              :default-active="activeTab"
              class="sidebar-menu"
              @select="handleMenuSelect"
            >
              <el-menu-item index="unpaid">
                <span>未付款</span>
              </el-menu-item>
              <el-menu-item index="paid">
                <span>已付款</span>
              </el-menu-item>
              <el-menu-item index="shipped">
                <span>已发货</span>
              </el-menu-item>
              <el-menu-item index="completed">
                <span>已收货</span>
              </el-menu-item>
              <el-menu-item index="cancelled">
                <span>已取消</span>
              </el-menu-item>
              <el-menu-item index="refund">
                <span>退货中</span>
              </el-menu-item>
              <el-menu-item index="return">
                <span>已退款</span>
              </el-menu-item>
              <el-menu-item index="all">
                <span>全部订单</span>
              </el-menu-item>
            </el-menu>
          </div>

          <!-- 右侧订单列表 -->
          <div class="main-panel">

            <!-- 订单列表 -->
            <div class="order-list">
              <div
                v-for="order in filteredOrders"
                :key="order.id"
                class="order-card"
              >
                <div class="order-header">
                  <div class="order-status">
                    <el-tag :type="getStatusType(order.status)" size="large">
                      {{ order.status }}
                    </el-tag>
                  </div>
                  <div class="order-info">
                    <span class="order-date">{{ order.date }}</span>
                    <span class="order-number">订单号: {{ order.orderNumber }}</span>
                    <span class="order-total">应付金额: {{ order.totalAmount }}元</span>
                  </div>
                </div>

                <div class="order-content">
                  <div class="product-info">
                    <img :src="order.productImage" :alt="order.productName" class="product-image" />
                    <div class="product-details">
                      <h4 class="product-name">{{ order.productName }}</h4>
                      <div class="product-specs">
                        <span>{{ order.productPrice }}元 x {{ order.quantity }}</span>
                      </div>
                    </div>
                  </div>
                  <div class="order-actions">
                    <el-button
                      type="primary"
                      size="small"
                      @click="viewOrderDetail(order.id)"
                    >
                      订单详情
                    </el-button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 分页 -->
            <div class="pagination-section">
              <el-pagination
                v-model:current-page="currentPage"
                :page-size="pageSize"
                :total="totalOrders"
                layout="prev, pager, next"
                @current-change="handlePageChange"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部服务保障 -->
    <div class="service-section">
      <div class="container">
        <div class="service-items">
          <div class="service-item">
            <el-icon class="service-icon"><CircleCheck /></el-icon>
            <span>正品保障</span>
          </div>
          <div class="service-item">
            <el-icon class="service-icon"><Clock /></el-icon>
            <span>7天无理由退货</span>
          </div>
          <div class="service-item">
            <el-icon class="service-icon"><Van /></el-icon>
            <span>15天免费换货</span>
          </div>
          <div class="service-item">
            <el-icon class="service-icon"><Coin /></el-icon>
            <span>满69元包邮</span>
          </div>
          <div class="service-item">
            <el-icon class="service-icon"><Lightning /></el-icon>
            <span>闪电发货</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { 
  ArrowLeft,
  CircleCheck, 
  Clock, 
  Van, 
  Coin, 
  Lightning 
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { findOrderByUserId as findOrderApi } from '@/api/order'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const activeTab = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const orders = ref([]) // 定义订单数据变量
const userStore = useUserStore() // 初始化用户store

// 返回上一页
const goBack = () => {
  router.back()
}

// 获取订单数据的函数
const loadOrders = (userId) => {
  if (!userId) {
    console.error('用户未登录或用户ID不存在')
    return
  }
  
  findOrderApi(userId).then((res) => {
    console.log('订单', res.data)
    orders.value = res.data || []
  }).catch(error => {
    console.error('获取订单失败', error)
    // 可以在这里添加错误提示
  })
}

onMounted(() => {
  // 从store中获取用户ID
  const userId = userStore.user.uid
  console.log('用户ID:', userId)
  loadOrders(userId)
})

// 过滤后的订单
const filteredOrders = computed(() => {
  if (activeTab.value === 'all') {
    return orders.value
  }
  return orders.value.filter(order => {
    const statusMap = {
      'unpaid': ['待付款'],
      'paid': ['已付款', '下单成功'],
      'shipped': ['已发货'],
      'completed': ['已完成', '已收货'],
      'cancelled': ['已取消'],
      'refund': ['退货中'],
      'return': ['已退款']
    }
    return statusMap[activeTab.value]?.includes(order.status)
  })
})

const totalOrders = computed(() => filteredOrders.value.length)

// 处理订单状态筛选
const handleMenuSelect = (index) => {
  activeTab.value = index
  currentPage.value = 1 // 切换状态时重置到第一页
}

// 根据订单状态获取标签类型
const getStatusType = (status) => {
  const statusMap = {
    '下单成功': 'success',
    '待付款': 'warning',
    '已付款': 'primary',
    '已发货': 'info',
    '已完成': 'success',
    '已取消': 'danger',
    '退货中': 'warning',
    '已退款': 'info'
  }
  return statusMap[status] || 'default'
}

// 查看订单详情
const viewOrderDetail = (orderId) => {
  console.log('查看订单详情:', orderId)
  // 后续可以添加订单详情页面的路由跳转
}

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page
}
</script>

<style scoped>
.order-management {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

/* Header */
.header {
  background: linear-gradient(135deg, #ff8c00 0%, #ffa500 100%);
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.header-content {
  display: flex;
  align-items: center;
  padding: 15px 0;
  gap: 30px;
}

.back-button {
  margin-left: 100px;
  color: #FF8C00 !important;
  font-size: 16px;
}


.back-button .el-icon {
  margin-right: 5px;
}

.page-title h2 {
  color: white;
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

/* Main Content */
.main-content {
  padding: 30px 0;
}

.content-wrapper {
  display: flex;
  gap: 30px;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

/* Sidebar */
.sidebar {
  width: 200px;
  background: #f8f9fa;
  padding: 30px 20px;
}

.sidebar-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 15px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.sidebar-menu {
  border: none;
  background: transparent;
}

:deep(.sidebar-menu .el-menu-item) {
  color: #666;
  font-size: 14px;
  height: 40px;
  line-height: 40px;
  margin-bottom: 5px;
  border-radius: 4px;
}

:deep(.sidebar-menu .el-menu-item:hover) {
  background-color: #fff4e6;
  color: #ff8c00;
}

:deep(.sidebar-menu .el-menu-item.is-active) {
  background-color: #ff8c00;
  color: white;
}

/* Main Panel */
.main-panel {
  flex: 1;
  padding: 30px;
}

.panel-header {
  margin-left: 20px;
}

.panel-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

/* Order List */
.order-list {
  margin-bottom: 30px;
}

.order-card {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  margin-bottom: 20px;
  overflow: hidden;
  transition: all 0.3s;
}

.order-card:hover {
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.order-header {
  background: #f8f9fa;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e0e0e0;
}

.order-info {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #666;
}

.order-content {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  object-fit: cover;
  background-color: #f0f0f0;
}

.product-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin: 0 0 8px 0;
}

.product-specs {
  font-size: 14px;
  color: #666;
}

/* Pagination */
.pagination-section {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

/* Service Section */
.service-section {
  background: #f8f9fa;
  padding: 30px 0;
  margin-top: 30px;
}

.service-items {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.service-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #666;
}

.service-icon {
  font-size: 24px;
  color: #ff8c00;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }

  .back-button {
    align-self: flex-start;
  }

  .content-wrapper {
    flex-direction: column;
  }

  .sidebar {
    width: 100%;
  }

  .order-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }

  .order-info {
    flex-direction: column;
    gap: 5px;
  }

  .order-content {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .service-items {
    flex-direction: column;
    gap: 20px;
  }
}
</style>